using IQIGame.Onigao.Game;
using System.Collections.Generic;

namespace IQIGame.Onigao.GamePlay
{
    public class EntitySmallPetComponent : TReusableEvtComponent
    {
        private readonly Dictionary<int, SmallPetEntity> _smallPets = new();
        public override void OnCreate(TEntity entity)
        {
            if (entity is not TViewEntity viewEntity)
            {
                return;
            }

            TryEnableGroup();
            _entity = viewEntity;
        }

        public override uint MaxStore => 4;

        public override void OnPoolReset()
        {
            _entity = null;
            _smallPets.Clear();
        }

        public void RemoveSmallPet(int pointId)
        {
            if (!_smallPets.Remove(pointId, out var smallPetEntity)) return;
            smallPetEntity.Free();
        }

        public void AddSmallPet(int pointId, int physicalEntityCid)
        {
            if (pointId == 0 || physicalEntityCid == 0)
            {
                return;
            }

            //同一挂点只能有一个小宠物
            RemoveSmallPet(pointId);
            var entity = SmallPetEntity.CreateEntity(_entity, pointId, physicalEntityCid);
            _smallPets.Add(pointId, entity);
        }

        public override void OnComponentEvent<T>(TComponentEvent eventType, T arg)
        {
            switch (eventType)
            {
                case TComponentEvent.OnEntityObjectLoaded:
                    //在实体加载完以后才开始创建默认小宠物实体
                    var heroData = PlayerModule.Instance.GetPlayerAvatarHeroData();
                    //遵循原GameAreaAccessUtil.GameAreaAccessUtil.GetHeroSkin的逻辑，在取不到时装cid时给一个默认值
                    var heroSkinCid = heroData.skinCid == 0 ? 100901 : heroData.skinCid;
                    var cfgHeroSkin = TableCenter.heroSkin.Get(heroSkinCid);
                    if (cfgHeroSkin != null)
                    {
                        AddSmallPet(cfgHeroSkin.SmallPetPoint, cfgHeroSkin.DefaultSmallPet);
                    }
                    break;
                case TComponentEvent.OnEntityObjectHided:
                    //卸载所有的小宠物实体
                    foreach (var smallPet in _smallPets.Values)
                    {
                        smallPet.Free();
                    }

                    _smallPets.Clear();
                    break;
            }
        }

        public override void OnUpdate(float deltaTime)
        {
            foreach (var smallPet in _smallPets.Values)
            {
                smallPet.OnUpdate(deltaTime);
            }
        }

        private void TryEnableGroup()
        {
            if (ManagerCenter.Entity.GetEntityGroup((int)EntityPoolGroupType.SmallPetEntity) == null)
            {
                ManagerCenter.Entity.EnableGroup((int)EntityPoolGroupType.SmallPetEntity);
            }
        }
    }
}